#include<bits/stdc++.h>

using namespace std;
typedef pair<int, int> PII;
const int N = 30;
const int dx[] = {1, -1, 0, 0}, dy[] = {0, 0, 1, -1};
int n, m;
char g[N][N];
int d[N][N][11][1030];
int cnt = 0;
map<PII, int> mp;

bool vaild(int x, int y) { return x > 0 && x <= n && y > 0 && y <= m; }

struct Node {
    int x, y, cnt, state;

    Node() {}

    Node(int x, int y, int cnt, int state) : x(x), y(y), cnt(cnt), state(state) {}
};

int bfs(int sx, int sy) {
    memset(d, -1, sizeof(d));
    queue<Node> Q;
    Q.push({sx, sy, 0, 0});
    d[sx][sy][0][0] = 0;
    while (!Q.empty()) {
        auto t = Q.front();
        Q.pop();
        int x = t.x, y = t.y, cnt = t.cnt, state = t.state;
        int dd = d[x][y][cnt][state];
        for (int i = 0; i < 4; i++) {
            int nx = x + dx[i], ny = y + dy[i];
            if (!vaild(nx, ny)) continue;
            if (g[nx][ny] == '#') continue;
            if (g[nx][ny] == 'E') return dd + 1;
            if (g[nx][ny] == '.') {
                if (d[nx][ny][cnt][state] != -1) continue;
                d[nx][ny][cnt][state] = dd + 1;
                Q.push({nx, ny, cnt, state});
            }
            if (g[nx][ny] == 'K') {
                PII now = {nx, ny};
                int id = mp[now];
                if (state & (1 << id)) {
                    if (d[nx][ny][cnt][state] != -1) continue;
                    d[nx][ny][cnt][state] = dd + 1;
                    Q.push({nx, ny, cnt, state});
                } else {
                    if (d[nx][ny][cnt + 1][state | (1 << id)] != -1) continue;
                    d[nx][ny][cnt + 1][state | (1 << id)] = dd + 1;
                    Q.push({nx, ny, cnt + 1, state | (1 << id)});
                }
            }
            if (g[nx][ny] == 'D' && cnt > 0) {
                if (d[nx][ny][cnt - 1][state] != -1) continue;
                d[nx][ny][cnt - 1][state] = dd + 1;
                Q.push({nx, ny, cnt - 1, state});
            }
        }
    }
    return -1;
}

void solve() {
    cin >> n >> m;
    for (int i = 1; i <= n; i++) cin >> g[i] + 1;
    int sx, sy;
    for (int i = 1; i <= n; i++)
        for (int j = 1; j <= m; j++)
            if (g[i][j] == 'S') sx = i, sy = j;
            else if (g[i][j] == 'K') {
                mp[make_pair(i, j)] = cnt;
                cnt++;
            }
    int ans = bfs(sx, sy);
    if (ans == -1) cout << "Bug Maze!!!";
    else cout << ans << '\n';
}

int main() {
    //freopen("1.in","r",stdin);
    ios::sync_with_stdio(false);
    cin.tie(0);
    solve();
    return 0;
}